package com.lkm.market2_0.m_imple.newDataUp;

import com.lkm.javatool.CollectionHelp;
import com.lkm.market2_0.ExpandConfig;
import com.lkm.market2_0.entity.SteelyardInfo;
import com.lkm.market2_0.m.dataUp.DataUpModule;
import com.lkm.market2_0.m.dataUp.SZUpdateStatus;
import com.lkm.market2_0.m.dataUp.SZWeightInfo;
import com.lkm.market2_0.m.steelyarddata.OrderEntity;

import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;



public class NewDataUpModuleImpl implements DataUpModule {
    private ThreadPoolExecutor THREAD_POOL_EXECUTOR;
    private static int CORE_POOL_SIZE = 5 * 3;
    private static int MAXIMUM_POOL_SIZE = 128;
    private static int KEEP_ALIVE = 1 * 3;

    public NewDataUpModuleImpl() {
        if (ExpandConfig.instance.isUI()) {
            CORE_POOL_SIZE = 1;
            MAXIMUM_POOL_SIZE = 2;
            KEEP_ALIVE = 1;
        }
        BlockingQueue<Runnable> sPoolWorkQueue = new SynchronousQueue<Runnable>();
        THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(
                CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
                TimeUnit.SECONDS, sPoolWorkQueue,
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.CallerRunsPolicy());
    }

    protected void execute(Runnable runnable) {
        THREAD_POOL_EXECUTOR.execute(runnable);
    }

    @Override
    public void upState(SteelyardInfo steelyardInfo, boolean isExceptions) {
        THREAD_POOL_EXECUTOR.execute(new Runnable() {
            @Override
            public void run() {
                upState_(steelyardInfo, isExceptions);
            }
        });
    }

    @Override
    public void submitWeightInfo(SteelyardInfo steelyardInfo, OrderEntity orderEntity) {
        THREAD_POOL_EXECUTOR.execute(new Runnable() {
            @Override
            public void run() {
                submitWeightInfoing(steelyardInfo, orderEntity);
            }
        });

    }


    
    protected void upState_(SteelyardInfo steelyardInfo, boolean isExceptions) {
        SZUpdateStatus szWeightInfo = com.lkm.market2_0.m_imple.newDataUp.NewDataUpParse.parseSZUpdateStatus(steelyardInfo, isExceptions);
        if (szWeightInfo != null) {
            NewSZApi.updateStatus(steelyardInfo.getSteelyardMac(),szWeightInfo, null, true);
        }
    }


    protected void submitWeightInfoing(SteelyardInfo steelyardInfo, OrderEntity orderEntity) {

        List<SZWeightInfo> szWeightInfos = NewDataUpParse.parseSZWeightInfo(steelyardInfo, orderEntity);

        if (!CollectionHelp.isEmpty(szWeightInfos)) {
//            orderEntity.goods.get(0), steelyardInfo.getStallEntity(),
            String json = NewSZApi.submitWeightInfo(steelyardInfo, szWeightInfos.toArray(new SZWeightInfo[szWeightInfos.size()]),  null, true);
        }
    }


}
